package org.oslims.server.service.impl;

import java.util.List;

import net.sf.gilead.gwt.GwtConfigurationHelper;
import net.sf.gilead.gwt.PersistentRemoteService;

import org.hibernate.Session;
import org.oslims.client.service.DepartmentService;
import org.oslims.domain.Department;
import org.oslims.server.dao.DepartmentDao;
import org.oslims.server.dao.hbm.HbmDepartmentDao;
import org.oslims.server.dao.util.HibernateUtil;

public class DepartmentServiceImpl extends PersistentRemoteService implements DepartmentService {

	private static final long serialVersionUID = 5545770962979309847L;

	DepartmentDao departmentDao;

	public DepartmentServiceImpl() {

		net.sf.gilead.core.hibernate.HibernateUtil hibernateUtil = new net.sf.gilead.core.hibernate.HibernateUtil(HibernateUtil.getSessionFactory());
		setBeanManager(GwtConfigurationHelper.initGwtStatelessBeanManager(hibernateUtil));

		departmentDao = new HbmDepartmentDao();
	}

	@Override
	// Saves or updates a department
	// Saves if id is null
	// Updates otherwise
	public void editDepartment(Department department) {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		try {
			departmentDao.setSession(session);
			departmentDao.makePersistent(department);
			session.getTransaction().commit();
		} catch (RuntimeException e) {
			session.getTransaction().rollback();
			throw new RuntimeException("The department allready exists!");
		} finally {
			session.close();
		}
	}

	@Override
	public void deleteDepartment(Department department) {
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		departmentDao.setSession(session);
		departmentDao.makeTransient(department);
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public List<Department> getAllDepartments() {
		Session session = HibernateUtil.getSession();

		departmentDao.setSession(session);

		List<Department> response = departmentDao.findAllWithLabResp("name");

		session.close();

		return response;
	}

	@Override
	public List<Department> getAllDepartments(int start, int length, String sortBy, boolean desc) {
		Session session = HibernateUtil.getSession();

		departmentDao.setSession(session);

		List<Department> response = departmentDao.findAllWithLabResp(start, length, sortBy, desc);

		session.close();

		return response;
	}

	@Override
	public Integer getDepartmentCount() {
		Session session = HibernateUtil.getSession();

		departmentDao.setSession(session);

		Integer response = departmentDao.getEntityCount();

		session.close();

		return response;
	}

}
